package com.ds.esd.localproxy.handler.dsm;

import com.ds.common.JDSException;
import com.ds.common.md5.MD5;
import com.ds.common.util.StringUtility;
import com.ds.config.JDSUtil;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.custom.CustomViewFactory;
import com.ds.esd.custom.bean.MethodConfig;
import com.ds.esd.editor.enums.PackagePathType;
import com.ds.esd.editor.enums.PackageType;
import com.ds.esd.localproxy.handler.AbstractRADHandler;
import com.ds.esd.project.ProjectCacheManager;
import com.ds.esd.tool.module.EUModule;
import com.ds.server.httpproxy.core.Handler;
import com.ds.server.httpproxy.core.HttpRequest;
import com.ds.server.httpproxy.core.HttpResponse;
import com.ds.server.httpproxy.core.Server;
import com.ds.vfs.FileInfo;
import com.ds.vfs.ct.CtVfsService;
import com.ds.vfs.ct.admin.CtAdminVfsServiceImpl;
import com.ds.web.RequestMethodBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Pattern;


public class DSMClsHandler extends AbstractRADHandler implements Handler {
    private static final Logger log = Logger.getLogger(com.ds.server.httpproxy.handler.ResourceHandler.class.getName());
    private String resourceMount;
    CtAdminVfsServiceImpl vfsClient;
    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        this.resourceMount = RESOURCE_MOUNT_OPTION.getProperty(server, handlerName);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {
        String path = request.getPath();
        boolean ruleMatches = rule.matcher(path).matches();
        if (!ruleMatches) {
            return false;
        }

        String projectName = this.getProjectName(request);
        boolean projectMatches = false;
        if (projectName != null) {
            Pattern projectRule = Pattern.compile(".*/(" + projectName + ")?.*");
            projectMatches = projectRule.matcher(path).matches();
        }
        if (!projectMatches) {
            return false;
        }
        RequestMethodBean requestMethodBean = getRequestMethodBean(request);

        String mimeType = getMimeType(path);
        String fullPath = this.formatPath(path, projectName);
        PackagePathType packagePathType = PackagePathType.startPath(fullPath);
        String classPath = StringUtility.replace(fullPath, ".js", "");
        classPath = StringUtility.replace(classPath, ".cls", "");
        String className = StringUtility.replace(classPath, getUrlPrefix(), ".");
        if (projectName.indexOf(ProjectCacheManager.VERSIONTOKEN) > -1) {
            projectName = projectName.split(ProjectCacheManager.VERSIONTOKEN)[0];
        }

        File file = null;
        if (packagePathType != null && packagePathType.getApiType().equals(PackageType.system)) {
            file = new File(JDSUtil.getJdsRealPath() + resourceMount + "/" + CustomViewFactory.DSMdsm + "/cls/" + MD5.getHashString(className));
        } else {
            file = new File(JDSUtil.getJdsRealPath() + resourceMount + getUrlPrefix() + projectName + "/cls/" + MD5.getHashString(className));
        }

        log.info("className=" + className + "  file=" + file.getPath());
        response.setMimeType(mimeType);
        if (file.exists()) {
            response.sendResponse(new FileInputStream(file), Integer.valueOf(Long.toString(file.length())));
            return true;
        } else {
            FileInfo fileInfo = null;
            try {
                fullPath = StringUtility.replace(fullPath, ".js", ".cls");
                EUModule module = null;
                if (packagePathType != null && packagePathType.getApiType().equals(PackageType.system)) {
                    fileInfo = ESDFacrory.getESDClient().getFileByPath(fullPath, CustomViewFactory.DSMdsm);
                    if (fileInfo != null) {
                        module = ProjectCacheManager.getInstance(ESDFacrory.getESDClient().getSpace()).loadEUClass(fileInfo.getPath(), CustomViewFactory.DSMdsm, false);
                    }
                } else {
                    fileInfo = ESDFacrory.getESDClient().getFileByPath(fullPath, projectName);
                    if (fileInfo != null) {
                        module = ProjectCacheManager.getInstance(ESDFacrory.getESDClient().getSpace()).loadEUClass(fileInfo.getPath(), projectName, false);
                    }
                }

                if (module != null) {
                    Map allParamsMap = this.getAllParamMap(null, request);
                    module.getComponent().fillFormValues(allParamsMap, false);
                    String json = ESDFacrory.getESDClient().genJSON(module, null).toString();
                    response.sendResponse(json, mimeType + ";");
                    return true;
                } else if (requestMethodBean != null) {
                    MethodConfig methodConfig = ESDFacrory.getESDClient().getMethodAPIBean(fullPath, projectName);
                    if (methodConfig != null && methodConfig.isModule()) {
                        return sendModule(className, request, response);
                    } else {
                        return false;
                    }
                }
            } catch (JDSException e) {
                e.printStackTrace();
            }
            return false;
        }

    }


    public CtVfsService getVfsClient() {
        if (vfsClient == null) {
            this.vfsClient = new CtAdminVfsServiceImpl();
        }
        return vfsClient;
    }
}
